package day02;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.JdbcUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/modify")
public class ModifyEmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ModifyEmpServlet.service");

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        Integer id=Integer.parseInt(request.getParameter("id"));
        String name=request.getParameter("name");
        String salaryStr=request.getParameter("salary");
        Double salary=salaryStr==null||"".equals(salaryStr.trim())
                ?null
                :Double.parseDouble(salaryStr);
        String sex=request.getParameter("sex");
        String eduStr=request.getParameter("edu");
        String edu="-1".equals(eduStr)
                ?null
                :eduStr;
        String[] hobbiesArr=request.getParameterValues("hobbies");
        String[] hobbies=hobbiesArr==null
                ?new String[]{}
                :hobbiesArr;
        String description=request.getParameter("description");


        System.out.println("id = " + id);
//
        Connection con=null;
        PreparedStatement ps=null;
        try{
            con= JdbcUtil.getConnection();
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("update t_emp ")
                    .append("set name=?, ")
                    .append("    salary=?, ")
                    .append("    sex=?, ")
                    .append("    edu=?, ")
                    .append("    hobbies=?, ")
                    .append("    description=? ")
                    .append("where id=? ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,name);
            ps.setDouble(2,salary);
            ps.setString(3,sex);
            ps.setString(4,edu);
            ps.setString(5, String.join(",", hobbies));
            ps.setString(6,description);
            ps.setInt(7,id);

            ps.executeUpdate();


            con.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally{
            JdbcUtil.close(null,ps,con);
        }

        response.sendRedirect(request.getContextPath()+"/list");

    }
}
